package com.crl.rcdp.gateway.filter;

import com.cars.util.request.RequestUtil;
import com.cars.util.string.StringUtil;
import com.crl.rcdp.sys.model.SysLog;
import com.crl.rcdp.sys.service.SysLogService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/8/10 23:27
 */
//@Component
public class PreRequestLogFilter extends ZuulFilter {
    @Autowired
    private SysLogService sysLogService;

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        System.out.print(String.format("send %s request to %s", request.getMethod(), request.getRequestURL()));
        //记录请求参数
        SysLog sysLog = new SysLog();
        String servletPath = request.getServletPath();//获取请求url
        String authorization = request.getHeader("Authorization");//获取authorization
        String appid = request.getHeader("appid");//appid
        String accessToken = request.getHeader("accessToken");//accessToken
        sysLog.setClientIp(StringUtil.getIp(request));//ip地址
        sysLog.setAuthType(FilterUtil.getAuthType(authorization, accessToken, appid));//授权方式
        sysLog.setPath(servletPath);//请求地址
        sysLog.setServiceName("");
        sysLog.setRequestParam(RequestUtil.getBody(request));//请求参数
        sysLog.setOwner(FilterUtil.getOwner(authorization, accessToken, appid));//owner
        if (sysLog.getRequestParam().length() > 2000) {
            sysLog.setRequestParam(sysLog.getRequestParam().substring(0, 2000));
        }
        sysLogService.add(sysLog);
        return null;
    }


}
